<template>
	<view class="master-form">
		<gyd-navbar back-color="#fff" :title="title"></gyd-navbar>

		<u-form class="form" labelPosition="left" :model="formData" :rules="rules" ref="formRef">
			<u-form-item class="form-item" label="水工姓名" labelWidth="100" prop="realname">
				<u-input v-model="formData.realname" placeholder="请输入水工姓名"></u-input>
			</u-form-item>
			<u-form-item class="form-item" label="联系方式" labelWidth="100" prop="contact_phone">
				<u-input v-model="formData.contact_phone" placeholder="请输入水工联系方式（登录账号）"></u-input>
			</u-form-item>

			<view class="tips">提示：师傅登录密码默认为:a123456，登录后可自行修改！</view>

			<u-form-item class="form-item" label="服务区域" labelWidth="100" prop="region_id">
				<uni-data-select v-model="formData.region_id" :localdata="regionList"
					@change="selectRegion"></uni-data-select>
			</u-form-item>

			<view class="form-item delivery-area">
				<text class="label">配送区域</text>
				<uni-data-select v-model="formData.province" :localdata="provinceList"
					@change="getCity"></uni-data-select>
				<uni-data-select v-model="formData.city" :localdata="cityList" @change="getArea"></uni-data-select>
			</view>

			<view class="form-row" v-if="areaList.length>0">
				<text class="label"></text>
				<view class="checkbox">
					<checkbox style="margin:20rpx 0 20rpx 0;" :checked="isAllSelectedArea" @click="selectAllArea">全选
					</checkbox>
					<checkbox-group class="checkbox-group" @change="toggleAllArea">
						<label v-for="(item, index) in areaList" :key="index">
							<checkbox :value="item.value" :checked="item.checked" />{{ item.label }}
						</label>
					</checkbox-group>
				</view>
			</view>

			<view class="form-row" v-if="townList.length>0">
				<text class="label"></text>
				<view class="checkbox">
					<checkbox style="margin:20rpx 0 20rpx 0;" :checked="isAllSelectedTown" @click="selectAllTown">全选
					</checkbox>
					<checkbox-group @change="toggleAllTown">
						<view class="area-item" v-for="(town,indexd) in townList" :key="indexd">
							<view class="area-name">—— {{town.areaName}} ——</view>
							<view class="town-item">
								<label v-for="(item, index) in town.townList" :key="index">
									<checkbox :value="item.value" :checked="item.checked" />{{ item.label }}
								</label>
							</view>
						</view>
					</checkbox-group>
				</view>
			</view>
		</u-form>

		<view class="footer">
			<view class="btn-group">
				<u-button type="primary" size="large" block @click="submit()">提交</u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const state = reactive({
		title: '添加水工',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		master_id: 0,
		store_id: 0,
		formData: {
			realname: '',
			contact_phone: '',
			region_id: 0,
			province: 0,
			city: 0,
			areas: '',
			towns: '',
		},
		regionList: [],
		provinceList: [],
		cityList: [],
		areaList: [],
		townList: [],
		province: 0,
		city: 0,
		area: 0,
		town: 0,
		isAllSelectedArea: false, // 区县全选状态
		areaItems: [], // 区县选择数据
		isAllSelectedTown: false, // 街道全选状态
		townItems: [], // 街道选择数据
	});

	const rules = ref([]);
	const formRef = ref();

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		if (opt.hasOwnProperty('master_id')) {
			console.log('传递参数', opt.master_id);
			state.master_id = opt.master_id;
			state.title = '编辑水工';
			getDetail();
		}
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	})

	onReachBottom(() => {
		console.log('触底加载更多');
	})

	function getDetail() {

	}

	function selectRegion(e) {
		console.log('选择服务区域', e);
	}

	function getCity() {
		if (!state.formData.province) {
			return
		}
		request.get('address/getAreaByPid', {
			pid: state.formData.province
		}).then(res => {
			state.cityList = res.data;
			if (state.city) state.formData.city = state.city
			state.cityList.forEach(item => {
				item.text = item.label; // 添加 text 属性
				item.value = item.value + ''; // 把 id 转成字符串
				delete item.label; // 删除 label 属性
			})
		})
	}

	function getArea() {
		if (!state.form.city) {
			return
		}
		request.get('address/getAreaByPid', {
			pid: state.form.city
		}).then(res => {
			state.areaList = res.data;
			if (state.area) state.form.area = state.area
			state.areaList.forEach(item => {
				item.value = item.value + ''; // 把 id 转成字符串
				item.checked = false; // 添加 checked 属性
			})
			state.isAllSelectedArea = false;
			state.areaItems = [];
			state.isAllSelectedTown = false;
			state.townItems = [];
			state.townList = [];
		})
	}

	function getTown() {
		console.log('getTown', state.areaItems);
		state.areaItems.forEach(area => {
			getAreaName(area);
		})
	}

	function getAreaName(area) {
		let areaName = '';
		request.get('address/areacityInfo', {
				id: area
			})
			.then(res => {
				console.log('区县', res);
				if (res.code == 1) {
					areaName = res.data.name;
					console.log('区县名', areaName);
					setTown(area, areaName);
				}
			})
	}

	function setTown(area, areaName) {
		request.get('address/getAreaByPid', {
				pid: area
			})
			.then(res => {
				console.log('街道', res);
				let data = {
					areaName: areaName,
					townList: res.data,
				}
				state.townList.push(data);
				console.log('街道-11', state.townList);
				state.townList.forEach(val => {
					console.log('街道-33-11', val);
					val.townList.forEach(item => {
						console.log('街道-33-22', item);
						item.value = item.value + ''; // 把 id 转成字符串
						item.checked = false; // 添加 checked 属性
					})
				})
				console.log('街道-22', state.townList);
				state.isAllSelectedTown = false;
				state.townItems = [];
			})
	}

	function selectAllArea() {
		console.log('selectAllArea', state.isAllSelectedArea);
		if (state.isAllSelectedArea) {
			//全选状态时取消全选
			state.areaList.forEach(item => {
				item.value = item.value + ''; // 把 id 转成字符串
				item.checked = false;
			})
			state.areaItems = [];
		} else {
			//非全选状态时全选
			state.areaList.forEach(item => {
				item.value = item.value + ''; // 把 id 转成字符串
				item.checked = true;
				state.areaItems.push(item.value);
			})
		}
		state.isAllSelectedArea = !state.isAllSelectedArea;
		state.townList = [];
		getTown();
	}

	function toggleAllArea(e) {
		console.log('toggleAllArea', e);
		state.areaItems = e.detail.value;
		state.areaList.forEach(item => {
			item.value = item.value + ''; // 把 id 转成字符串
			state.areaItems.forEach(area => {
				if (item.value == area) {
					console.log(item.label + '选中');
					item.checked = true; // 更新所有子项状态
				}
			})
		});

		// 更新全选状态
		console.log(state.areaItems.length, state.areaList.length)
		if (state.areaItems.length == state.areaList.length) {
			state.isAllSelectedArea = true;
		} else {
			state.isAllSelectedArea = false;
		}
		console.log('区县全选状态', state.isAllSelectedArea);
		state.isAllSelectedTown = false;
		state.townItems = [];
		state.townList = [];
		getTown();
	}

	function selectAllTown() {
		console.log('selectAllTown', state.isAllSelectedTown, state.townList);
		state.townItems = []; // 清空已选街道数据
		if (state.isAllSelectedTown) {
			//全选状态时取消全选
			state.townList.forEach(town => {
				town.townList.forEach(item => {
					item.value = item.value + ''; // 把 id 转成字符串
					item.checked = false;
				})
			})
			console.log('街道未全选', state.townItems);
		} else {
			//非全选状态时全选
			state.townList.forEach(town => {
				town.townList.forEach(item => {
					item.value = item.value + ''; // 把 id 转成字符串
					item.checked = true;
					state.townItems.push(item.value);
				})
			})
			console.log('街道全选', state.townItems);
		}
		state.isAllSelectedTown = !state.isAllSelectedTown;
	}

	function toggleAllTown(e) {
		console.log('toggleAllTown', e);
		state.townItems = e.detail.value;
		let len = 0;
		console.log('toggleAllTown-townList', state.townList);
		state.townList.forEach(temp => {
			console.log('temp', temp);
			len += temp.townList.length;
			console.log('len', len);
			temp.townList.forEach(item => {
				item.value = item.value + ''; // 把 id 转成字符串
				state.townItems.forEach(town => {
					if (item.value == town) {
						console.log(item.label + '选中');
						item.checked = true; // 更新所有子项状态
					}
				})
			})
		});

		// 更新全选状态
		console.log('length', state.townItems.length, len);
		if (state.townItems.length == len) {
			state.isAllSelectedTown = true;
		} else {
			state.isAllSelectedTown = false;
		}
		console.log('街道全选状态', state.isAllSelectedTown);
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		master_id,
		store_id,
		formData,
		regionList,
		provinceList,
		cityList,
		areaList,
		townList,
		province,
		city,
		area,
		town,
		isAllSelectedArea,
		areaItems,
		isAllSelectedTown,
		townItems,
	} = toRefs(state);
</script>

<style lang="scss">
	.master-form {
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));

		.form {
			padding: $m24;

			.form-item {
				background: #fff;
				margin-bottom: $m16;
				padding: 0 $m24;
				border-radius: 10rpx;
			}

			.delivery-area {
				@include f-between($align: center);
				height: 80rpx;
				background: #fff;
				margin-bottom: $m16;
				padding: 0 $m24;
				border-radius: 10rpx;

				.label {
					width: 128rpx;
					// color: $tips-color;
				}

				.value {
					flex: 1;
					color: $main-color;
				}

				:deep(.uni-select) {
					border: none;
				}
			}

			.tips {
				padding: $m24;
			}

			.form-row {
				@include f-between($align: center);
				background: #fff;
				margin-bottom: $m16;
				padding: 0 $m24;
				border-radius: 10rpx;

				.label {
					width: 128rpx;
					color: $tips-color;
				}

				.value {
					flex: 1;
					color: $main-color;
				}

				:deep(.uni-select) {
					border: none;
				}

				.area-name {
					padding: 20rpx 0;
					text-align: center;
				}

				.checkbox {
					.checkbox-group {
						display: flex;
						flex-wrap: wrap;
					}

					.town-item {
						display: flex;
						flex-wrap: wrap;
					}

					.uni-label-pointer {
						width: 25%;
						margin: 0 0rpx 20rpx 0;
					}

				}
			}
		}

		.footer {
			position: fixed;
			/* 固定在底部 */
			bottom: 0;
			width: 100%;

			.btn-group {}
		}
	}
</style>